package hk.ust.comp3111.ustnutrition;

import hk.ust.comp3111.ustnutrition.data.ApiHandler;
import hk.ust.comp3111.ustnutrition.data.DataAccessor;
import hk.ust.comp3111.ustnutrition.data.DataTableListener;
import hk.ust.comp3111.ustnutrition.data.db.IntakeRecord;
import hk.ust.comp3111.ustnutrition.data.json.ApiResponseStatistics;
import hk.ust.comp3111.ustnutrition.formula.ScoreCalculator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.GraphViewSeries.GraphViewSeriesStyle;
import com.jjoe64.graphview.LineGraphView;

public class StatisticFragment extends Fragment implements DataTableListener<IntakeRecord>
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		DataAccessor.Instance.getRecords().addChangeListener(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		DataAccessor.Instance.getRecords().removeChangeListener(this);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// String message = getArguments().getString(EXTRA_MESSAGE);
		View v = inflater.inflate(R.layout.statistic_frag, container, false);
		// TextView messageTextView = (TextView)v.findViewById(R.id.textView);
		// messageTextView.setText(message);

		infoTxt = (TextView) v.findViewById(R.id.score);
		mRankBtn = (Button)v.findViewById(R.id.rank);
		mRankBtn.setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						onRankClick();
					}
				});

		graphView = new LineGraphView(container.getContext(), "");

		graphView.getGraphViewStyle().setGridColor(Color.CYAN);
		graphView.getGraphViewStyle().setHorizontalLabelsColor(Color.BLACK);
		graphView.getGraphViewStyle().setVerticalLabelsColor(Color.BLACK);
		graphView.getGraphViewStyle().setTextSize(MiscUtils.spToPx(getActivity(), 12));// getResources().getDimension(R.dimen.big));
		graphView.getGraphViewStyle().setNumHorizontalLabels(5);
		graphView.getGraphViewStyle().setNumVerticalLabels(10);
		((LineGraphView) graphView).setDrawDataPoints(true);
		((LineGraphView) graphView).setDataPointsRadius(3f);

		LinearLayout layout = (LinearLayout)v.findViewById(R.id.graph1);
		layout.addView(graphView);
		graphView.setVisibility(View.GONE);

		updateData();
		return v;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
	{
		inflater.inflate(R.menu.stat, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
		case R.id.share:
			onShareClick();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void updateData() {
		infoTxt.setText("Your weekly score is " + (int)(cal.getWeeklyScore() * 10) / 10.0);
		DataAccessor.Instance.statistics(new ApiHandler<ApiResponseStatistics>() {
			@Override
			public void onSuccess(ApiResponseStatistics response)
			{
				GraphView.GraphViewData[] datas = new GraphView.GraphViewData[response.getLength()];
				double maxVal = 0;
				for(int i = 0; i < datas.length; i++) {
					datas[i] = new GraphView.GraphViewData(response.getX(i), response.getY(i));
					if(response.getY(i) > maxVal)
						maxVal = response.getY(i);
				}

				GraphViewSeries series = new GraphViewSeries("Curve",
						new GraphViewSeriesStyle(Color.BLACK, 3),
						datas);

				double score = cal.getWeeklyScore();

				GraphViewSeries myPlace = new GraphViewSeries("Point",
						new GraphViewSeriesStyle(Color.RED, 3),
						new GraphView.GraphViewData[] { new GraphViewData(score, 0.0d),
								new GraphViewData(score, maxVal) });

				graphView.removeAllSeries();
				graphView.addSeries(series);
				graphView.addSeries(myPlace);

				graphView.setVisibility(View.VISIBLE);
			}

			@Override
			public void onFailure(String message)
			{
				Toast.makeText(getActivity(), "Failed retrieving data from the server",
						Toast.LENGTH_LONG).show();
			}
		});
	}

	private void onShareClick()
	{
		Intent sendIntent = new Intent();
		sendIntent.setAction(Intent.ACTION_SEND);
		sendIntent.putExtra(Intent.EXTRA_TEXT,
				"I got " + (int)(cal.getWeeklyScore() * 10) / 10.0
						+ " on UST Nutrition this week");
		sendIntent.setType("text/plain");
		startActivity(Intent.createChooser(sendIntent, "Share to..."));
	}

	private void onRankClick()
	{
		startActivity(new Intent(getActivity(), UserRankActivity.class));
	}

	private GraphView graphView;
	private TextView infoTxt;
	private Button mRankBtn;
	private ScoreCalculator cal = new ScoreCalculator(DataAccessor.Instance.getUser());

	Handler handler = new Handler();
	boolean dirty;

	@Override
	public void changed(DataTableListener.ChangeEvent<IntakeRecord> event) {
		dirty = true;
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				if(dirty) {
					dirty = false;
					if (graphView != null) {
						updateData();
					}
				}
			}
		}, 500);
	}
}
